import operator
import sys
import math

def main(profile_file, group_file, out_file, top_tag = 2000):
	topTags = {}
	with open("tag.stat") as fi:
		for i in range(top_tag):
			line = fi.readline()
			tag = int(line.split()[0])
			rank = int(line.split()[2])
			topTags[tag] = rank

	utag = {}
	with open(profile_file) as fi:
		for line in fi:
			uid = int(line.split()[0])
			tags = map(int, line.split()[4].split(';'))
			utag[uid] = []
			for tag in tags:
				if tag != 0 and tag in topTags:
					utag[uid].append(tag)

	with open(group_file) as fi, open(out_file, "w") as fo:
		fo.write("%d\n" % top_tag)
		last_uid = -1
		for line in fi:
			arr = map(int, line.split())
			uid = arr[0]; iid = arr[1]
			if uid != last_uid:
				last_uid = uid
				if uid not in utag or len(utag[uid]) == 0:
					fo.write("0\n")
					continue
				fo.write("%d" % len(utag[uid]))
				v = 1.0 / math.sqrt(len(utag[uid]))
				for tag in utag[uid]:
					fo.write(" %d:%f" % (topTags[tag], v))
				fo.write("\n")

if __name__ == "__main__":
	if len(sys.argv) < 4:
		print "usage: user_profile.ridx train.group train.group.tag.imfb [top_tag]"
	elif len(sys.argv) == 4:
		main(sys.argv[1], sys.argv[2], sys.argv[3])
	else:
		main(sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4]))
